package cn.iocoder.boot.springai001.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.Page;
import cn.hutool.json.JSONObject;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;


public record DBService(DataSource dataSource) {

    public static DBService instance(DataSource dataSource) {
        return new DBService(dataSource);
    }

    public JSONObject getOne(String sql, Object... params) throws SQLException {
        return BeanUtil.toBean(db().queryOne(sql, params), JSONObject.class);
    }

    public List<JSONObject> list(String sql) throws SQLException {
        return pageConverterListJsonObject(db().query(sql));
    }

    public <T> T getOne(String sql, Class<T> clazz, Object... params) throws SQLException {
        return BeanUtil.toBean(db().queryOne(sql, params), clazz);
    }

    public <T> List<T> list(String sql, Class<T> clazz) throws SQLException {
        return db().query(sql, clazz);
    }

    public <T> List<T> list(String sql, Class<T> clazz, Object... params) throws SQLException {
        return db().query(sql, clazz, params);
    }

    private Page pageInstance(int pageNum, int pageSize) {
        return new Page(pageNum > 0 ? pageNum - 1 : pageNum, pageSize);
    }

    private List<JSONObject> pageConverterListJsonObject(List<Entity> list) {
        return list.stream().map(entity -> BeanUtil.toBean(entity, JSONObject.class)).collect(Collectors.toList());
    }

    private Db db() {
        return Db.use();
    }

}
